package org.langqiao.network.socket;

import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class ChatTCPSocketJFrame extends JFrame implements ActionListener
{
	private String name;
	private Socket socket;
	private JTextField text_sender;//定义一个文本行发送者
	private JTextArea text_receiver;
	private JButton button_send,button_leave;//定义两个按钮，一个是发送按钮，一个是离线按钮
	private PrintWriter cout;//字符输出流
	public ChatTCPSocketJFrame(String name,Socket socket)throws IOException//构造方法
	{
		super("聊天室	"+name+"	"+InetAddress.getLocalHost());//窗口框架的标题名
		this.setBounds(320,240,360,240);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.text_receiver=new JTextArea();
		this.text_receiver.setEditable(false);//文本区不可编辑
		this.getContentPane().add(new JScrollPane(this.text_receiver));
		
		JPanel panel=new JPanel();//实例化一个面板
		this.getContentPane().add(panel,"South");//在窗口框架的最南面添加一个Panel面板
		this.text_sender=new JTextField(16);//一个16列的文本行
		panel.add(this.text_sender);//在面板panel中添加text_sender文本行
		button_send=new JButton("发送");
		panel.add(button_send);//在面板中添加发送按钮
		button_send.addActionListener(this);//为发送按钮注册事件监听器
		button_leave=new JButton("离线");
		panel.add(button_leave);
		button_leave.addActionListener(this);
		this.setVisible(true);//设置窗口框架可见
		
		this.name=name;
		this.socket=socket;
		this.cout=new PrintWriter(socket.getOutputStream(),true);//获得Socket的输出流，立即flush
		this.cout.println(name);//发送自己网名给对方
		
		BufferedReader cin=new BufferedReader(new InputStreamReader(socket.getInputStream()));//获得socket对象的输入流，创建字符输入流
		String aline=cin.readLine();//接收对方网名
		text_receiver.append("连接"+aline+"成功"+"\r\n");//显示对方发送来的内容
		aline=cin.readLine();
		while(aline!=null&&!aline.equals("bye"))//从输入流接收对方发来的字符窜,bye是约定的离线信息
		{
			text_receiver.append(aline+"\r\n");
			aline=cin.readLine();
		}
		cin.close();
		cout.close();
		socket.close();//关闭socket连接
		button_send.setEnabled(false);
		button_leave.setEnabled(false);
	}
	public ChatTCPSocketJFrame(String name,String host,int port)throws IOException
	{
		this(name,new Socket(host,port));//客户端向指定主机端口发送TCP连接请求
	}
	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource()==button_send)//发送按钮
		{
			this.cout.println(name+" 说："+text_sender.getText());//通过流发送给对方
			text_receiver.append("我说："+text_sender.getText()+"\n");
			text_sender.setText("");
		}
		if(e.getSource()==button_leave)//离线按钮
		{
			text_receiver.append("我离线\n");
			this.cout.println(name+"离线\n"+"bye");//发送给对方离线约定
			button_send.setEnabled(false);
			button_leave.setEnabled(false);
			
			
		}
	}
//	主函数
	public static void main(String[] args)throws IOException
	{//客户端向指定主机端口发送TCP连接请求
		new ChatTCPSocketJFrame("小蜜蜂","202.119.161.101",2001);
		
	}
}